package cn.mmko.domain.strategy.service.armory;

import cn.mmko.domain.strategy.model.entity.StrategyAwardEntity;
import cn.mmko.domain.strategy.model.entity.StrategyEntity;
import cn.mmko.domain.strategy.model.entity.StrategyRuleEntity;
import cn.mmko.domain.strategy.repository.IStrategyRepository;
import cn.mmko.types.enums.ResponseCode;
import cn.mmko.types.exception.AppException;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;
@Repository
public class StrategyArmoryDispatch implements IStrategyArmory,IStrategyDispatch{
    @Resource
    private IStrategyRepository strategyRepository;
    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {
        //查询策略key
        List<StrategyAwardEntity> strategyAwardEntities=strategyRepository.queryStrategyAwardList(strategyId);
        assembleLotteryStrategy(String.valueOf(strategyId),strategyAwardEntities);
        //权重规则配置
        StrategyEntity strategyEntity = strategyRepository.queryStrategyEntityByStrategyId(strategyId);//策略信息
        String ruleWeight = strategyEntity.getRuleWeight();//权重规则
        if(null==ruleWeight) return true;
        StrategyRuleEntity strategyRuleEntity=strategyRepository.queryStrategyRule(strategyId,ruleWeight);//权重规则信息
        if(null==strategyRuleEntity){
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(),ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());

        }
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();//权重规则值
        Set<String> keySet = ruleWeightValueMap.keySet();//获取权重规则组
        for (String key : keySet) {
            List<Integer> values = ruleWeightValueMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);//策略奖品列表的副本
            strategyAwardEntitiesClone.removeIf(entity->!values.contains(entity.getAwardId()));//获取指定权重规则的策略奖品列表
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_".concat(key)),strategyAwardEntitiesClone);//递归组装策略


        }//权重规则组循环


        return true;
    }
    private void assembleLotteryStrategy(String key,List<StrategyAwardEntity> strategyAwardEntities){
        BigDecimal minRate= strategyAwardEntities.stream().map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);//最小概率
        BigDecimal totalRate= strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO,BigDecimal::add);//总概率
        BigDecimal rateRange = totalRate.divide(minRate, 0, RoundingMode.CEILING);//概率区间
        List<Integer> strategyAwardSearchTables = new ArrayList<>(rateRange.intValue());//策略抽奖表
        for(StrategyAwardEntity strategyAwardEntity:strategyAwardEntities){
            Integer awardId = strategyAwardEntity.getAwardId();
            BigDecimal awardRate = strategyAwardEntity.getAwardRate();
            for(int i=0;i<rateRange.multiply(awardRate).setScale(0,RoundingMode.CEILING).intValue();i++){
                strategyAwardSearchTables.add(awardId);
            }//每个奖品的概率区间，概率乘以区间，然后取整，区间就是最小概率在总概率中的的占比
        }
        Collections.shuffle(strategyAwardSearchTables);//打乱随机顺序
        Map<Integer, Integer> shuffleStrategyAwardSearchTables = new LinkedHashMap<>();
        for(int i=0;i<strategyAwardSearchTables.size();i++){
            shuffleStrategyAwardSearchTables.put(i,strategyAwardSearchTables.get(i));
        }//用Map存入抽奖表，键为索引，值为奖品id
        //redis 存储
        strategyRepository.storeStrategyAwardSearchTables(key,shuffleStrategyAwardSearchTables.size(),shuffleStrategyAwardSearchTables);

    }
    @Override
    public Integer getRandomAwardId(Long strategyId) {
        int rateRange = strategyRepository.getRateRange(strategyId);//获取概率区间
        return strategyRepository.getStrategyAwardAssemble(String.valueOf(strategyId),new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Integer getRamdomAwardId(Long strategyId, String ruleWeight) {
        String key = String.valueOf(strategyId).concat("_".concat(ruleWeight));
        int rateRange = strategyRepository.getRateRange(key);
        return strategyRepository.getStrategyAwardAssemble(key,new SecureRandom().nextInt(rateRange));//
    }
}
